﻿using log4net;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp4
{
    /// <summary>
    /// MultipleWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MultipleWindow : Window
    {
        public static ILog log = LogManager.GetLogger(typeof(MultipleWindow));
        private String userName = ConfigurationManager.AppSettings["userName"];
        private String token = ConfigurationManager.AppSettings["token"];

        public MultipleWindow()
        {
            InitializeComponent();

            #region 启动时串口最大化显示
            Rect rc = SystemParameters.WorkArea; //获取工作区大小
            this.Left = 0; //设置位置
            this.Top = 0;
            this.Width = rc.Width;
            this.Height = rc.Height;
            #endregion


        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            log.Debug("Window_Loaded start.");
        
            try
            {
                int childrenCount = VisualTreeHelper.GetChildrenCount(this.grid);
                // 遍历所有浏览器
                for (int i = 0; i < childrenCount; i++)
                {
                    var childBorder = VisualTreeHelper.GetChild(this.grid, i);

                    var child = VisualTreeHelper.GetChild(childBorder, 0);
                    if (child.GetType().Name == "WebView2")
                    {
                        var webView = child as Microsoft.Web.WebView2.Wpf.WebView2;
                         await webView.EnsureCoreWebView2Async();
                        webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;

                        await webView.CoreWebView2.ExecuteScriptAsync("localStorage.setItem(\"accout-token\",\"" + token + "\")");
                        await webView.CoreWebView2.ExecuteScriptAsync("localStorage.setItem(\"user_account\",\"" + userName + "\")");

                        String url = ConfigurationManager.AppSettings[webView.Name];
                        webView.CoreWebView2.Navigate(url);
                        log.Debug("webView:" + webView.Name + " =" + url);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Window_Loaded Exception.", ex);
            }



            log.Debug("Window_Loaded end.");
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
        }
    }
}
